package semant.second_pass;

import semant.Env;
import symbol.ClassInfo;
import symbol.Symbol;
import syntaxtree.BooleanType;
import syntaxtree.IdentifierType;
import syntaxtree.IntArrayType;
import syntaxtree.IntegerType;
import syntaxtree.Type;

class TypeHandler {

    static boolean compatible(Env env, Type target, Type source) {
        
    	// primeiro os testes simples, sem heranca
    	if (target instanceof IntegerType) {
			return source instanceof IntegerType;
		} else if (target instanceof BooleanType) {
			return source instanceof BooleanType;
		} else if (target instanceof IntArrayType) {
			return source instanceof IntArrayType;
		}
        
        // agora testamos a heranca
        if (!(source instanceof IdentifierType)) {
			return false;
		}
        
        ClassInfo c1 = env.classes.get(Symbol.symbol(((IdentifierType)target).name));
        ClassInfo c2 = env.classes.get(Symbol.symbol(((IdentifierType)source).name));
        
        // agora, percorremos a hierarquia para ver se as classes batem
        if (c1 == null) {
			return false;
		}
        
        while (c2 != null) {
        	if (c2.name == c1.name) {
				return true;
			} else {
				c2 = c2.base;
			}
        }
        
        return false;
    }

}
